﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using TomNet.AspNetCore.Mvc;
using TomNet.SqlSugarCore.Entity;
using Microsoft.Extensions.DependencyInjection;
using TomNet.AspNetCore.Data;
using TomNet.Data;
using TomNet.App.Model.DB;
using TomNet.App.Core.Contracts;
using TomNet.Security.Claims;
using TomNet.App.Model.DTO;
using TomNet.App.Model.DB.Identity;
using SqlSugar;

namespace TomNet.App.Web.Controllers.API
{
	public partial class PageController : Common.APIController
    {
        #region AjaxResult OptionsList()

        [HttpPost]
		public AjaxResult OptionsList(OptionsParameter parameter)
		{           
            int total = 0;
            var data = _unitOfWork.DbContext.Queryable<Options>().Select(m => new OptionsModel
            {
                Name = m.Name,
                Value = m.Value,
                Remark = m.Remark,

            });          
            //分页及数据处理            
            var list = data.ToPageList(parameter.Page, parameter.Limit, ref total);            
            //返回数据
            var result = new OptionsParameterModel
            {
                Rows = list,
                Total = total
            };
            return new AjaxResult("允许访问", AjaxResultType.Success, result);
		}
       
        public class OptionsModel
        {
            public string Name { get; set; }            
            public string Value { get; set; }            
            public string Remark { get; set; }
        }
        public class OptionsParameter
        {
            public int Page { get; set; } = 1;
            public int Limit { get; set; } = 20;
        }

        public class OptionsParameterModel
        {
            public List<OptionsModel> Rows { get; set; } = new List<OptionsModel>();
            public int Total { get; set; }
        }

        #endregion
        #region AjaxResult ProductList() 产品列表

        [HttpPost]
        public AjaxResult ProductList(ProductParameter parameter)
        {            
            int total = 0;            
            var data2 = _unitOfWork.DbContext.Queryable<Coin>().Single(it => it.Id == 1);
            var data = _unitOfWork.DbContext.Queryable<Product>().Select(m => new ProductModel
            {
                Id = m.Id,
                Title = m.Title,
                Name = m.Name,
                Hashrate = m.Hashrate,
                Inventory = m.Inventory,
                ElectricCharge = m.ElectricCharge,
                Price = m.Price,
                Effective = "永久",
                DayIncome = Convert.ToDecimal(m.Hashrate) * BTCPoolDetails.Throughput,
                Cycle = m.Cycle,
                Recommend = m.Recommend,

            });
            //分页及数据处理            
            var list = data.ToPageList(parameter.Page, parameter.Limit, ref total);
            //返回数据
            var result = new ProductParameterModel
            {
                Rows = list,
                Total = total
            };            
            return new AjaxResult("允许访问", AjaxResultType.Success, result);
        }

        public class ProductModel
        {
            public int Id { get; set; }
            public string Title { get; set; }
            public string Name { get; set; }
            /// <summary>
            /// 算力
            /// </summary>
            public float Hashrate { get; set; }           
            /// <summary>
            /// 库存
            /// </summary>
            public int Inventory { get; set; }            
            /// <summary>
            /// 电费
            /// </summary>
            public decimal ElectricCharge { get; set; }            
            /// <summary>
            /// 价格
            /// </summary>
            public decimal Price { get; set; }
            /// <summary>
            /// 有效期
            /// </summary>
            public string Effective { get; set; }
            /// <summary>
            /// 预计日产出
            /// </summary>
            public decimal DayIncome { get; set; }
            /// <summary>
            /// 回本周期
            /// </summary>
            public int Cycle { get; set; }
            /// <summary>
            /// 是否推荐
            /// </summary>
            public bool Recommend { get; set; }
        }
        public class ProductParameter
        {
            public int Page { get; set; } = 1;
            public int Limit { get; set; } = 20;
        }

        public class ProductParameterModel
        {
            public List<ProductModel> Rows { get; set; } = new List<ProductModel>();
            public int Total { get; set; }
        }

        #endregion
        #region AjaxResult ProductInfo()  产品详情

        [HttpPost]
        public AjaxResult ProductInfo(ProductInfoParameter parameter)
        {
            int total = 0;
            var data2 = _unitOfWork.DbContext.Queryable<Coin>().Single(it => it.Id == 1);
            var data = _unitOfWork.DbContext.Queryable<Product>().Where(m=>m.Id==parameter.Id).Select(m => new ProductInfoModel
            {
                Id = m.Id,
                Name = m.Name,
                Hashrate = m.Hashrate,
                Inventory = m.Inventory,
                ElectricCharge = m.ElectricCharge,
                Price = m.Price,
                Effective = "永久",
                DayIncome = m.Hashrate * data2.DayIncome,
                Remark = m.Remark,
                Image = m.Image,

            }); 
            //分页及数据处理            
            var list = data.ToPageList(parameter.Page, parameter.Limit, ref total);
            //返回数据
            var result = new ProductInfoParameterModel
            {
                Rows = list,
                Total = total
            };
            return new AjaxResult("允许访问", AjaxResultType.Success, result);
        }

        public class ProductInfoModel
        {       
            public int Id { get; set; }
            public string Name { get; set; }
            /// <summary>
            /// 算力
            /// </summary>
            public float Hashrate { get; set; }
            /// <summary>
            /// 库存
            /// </summary>
            public int Inventory { get; set; }
            /// <summary>
            /// 电费
            /// </summary>
            public decimal ElectricCharge { get; set; }
            /// <summary>
            /// 价格
            /// </summary>
            public decimal Price { get; set; }
            /// <summary>
            /// 有效期
            /// </summary>
            public string Effective { get; set; }
            /// <summary>
            /// 预计日产出
            /// </summary>
            public float DayIncome { get; set; }
            public string Remark { get; set; }
            public string Image { get; set; }


        }
        public class ProductInfoParameter
        {
            public int Page { get; set; } = 1;
            public int Limit { get; set; } = 20;
            public int Id { get; set; }
        }

        public class ProductInfoParameterModel
        {
            public List<ProductInfoModel> Rows { get; set; } = new List<ProductInfoModel>();
            public int Total { get; set; }
        }

        #endregion
        #region AjaxResult MyAward() 我的奖励

        [HttpPost]
        public AjaxResult MyAward(MyAwardParameter parameter)
        {
            int total = 0;            
            var data = _businessContract.UnitOfWork.DbContext.Queryable<UserRewardBusiness, Business, Users>((u, b, us) => u.BusinessID == b.Id
             && b.UserId == us.Id).OrderBy((u, b, us) => u.CreatedTime)
			 .Where((u, b, us) =>u.UserID == LoginUserId)
            .Select((u, b, us) => new MyAwardModel
            {
                Id = u.Id,
                Hashrate = u.Hashrate,
                BeginTime = u.BeginTime,
                EndTime = u.EndTime,
                CreatedTime = u.CreatedTime,
                AwardName = b.ProductName,
                UserName = us.UserName,
                ProductName = b.ProductName,
                BHashrate = b.Hashrate,
                Number = b.Number,
                ProfitAll = _businessIncomeRunningsContract.Entities.AsQueryable().Where(p => p.Id == u.Id).Sum(p => p.Amount),
                ElectricityAll = _businessIncomeRunningsContract.Entities.AsQueryable().Where(p => p.Id == u.Id).Sum(p => p.ElectricCharge),
                AwardAll = SqlFunc.Subqueryable<UserRewardBusiness>().Where(m => m.Id == u.Id).Sum(m => m.Hashrate),
                ShengXiaoAll = SqlFunc.Subqueryable<UserRewardBusiness>().Where(m => m.Id == u.Id && (m.BeginTime < DateTime.Now && m.EndTime > DateTime.Now)).Sum(m => m.Hashrate),
                WeiShengXiaoAll = SqlFunc.Subqueryable<UserRewardBusiness>().Where(m => m.Id == u.Id && (m.BeginTime > DateTime.Now)).Sum(m => m.Hashrate),
                Salesman = _unitOfWork.DbContext.Queryable<Users>().Single(p=>p.Id == _unitOfWork.DbContext.Queryable<UserMap>().Single(it => it.UserId == us.Id && it.AgentId == b.UserId).AgentSalesmanId).UserName,
        });
           
            MyAwardModel entity = data.First() ?? new MyAwardModel();

            //分页及数据处理            
            var list = data.ToPageList(parameter.Page, parameter.Limit, ref total);
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].BeginTime < DateTime.Now && list[i].EndTime > DateTime.Now)
                {
                    list[i].State = "已生效";
                }
                else if (list[i].BeginTime > DateTime.Now)
                {
                    list[i].State = "未生效";
                }
                else if (list[i].EndTime < DateTime.Now)
                {
                    list[i].State = "已过期";
                }
            }
            //返回数据
            var result = new MyAwardParameterModel
            {
                Rows = list,
                Total = total
            };
            return new AjaxResult("允许访问", AjaxResultType.Success, result);
        }
        public class MyAwardParameter
        {
            public int Page { get; set; } = 1;
            public int Limit { get; set; } = 20;
        }

        public class MyAwardParameterModel
        {
            public List<MyAwardModel> Rows { get; set; } = new List<MyAwardModel>();
            public int Total { get; set; }
        }

        public class MyAwardModel
        {
            public int Id { get; set; }
            //奖励
            public float Hashrate { get; set; }            
            public DateTime BeginTime { get; set; }
            public DateTime EndTime { get; set; }
            public DateTime CreatedTime { get; set; }
            public string AwardName { get; set; }
            //订单
            public string UserName{ get; set; }           
            /// <summary>
            /// 矿机名称
            /// </summary>
            public string ProductName { get; set; }
            /// <summary>
            /// 算力
            /// </summary>
            public decimal BHashrate { get; set; }
            
            /// <summary>
            /// 购买数量
            /// </summary>
            public int Number { get; set; }
            /// <summary>
            /// 总收益
            /// </summary>
            public decimal ProfitAll { get; set; }
            /// <summary>
            /// 总电费
            /// </summary>
            public decimal ElectricityAll { get; set; }
            /// <summary>
            /// 状态
            /// </summary>
            public string State { get; set; }
            /// <summary>
            /// 总奖励
            /// </summary>
            public float AwardAll { get; set; }
            /// <summary>
            /// 生效
            /// </summary>
            public float ShengXiaoAll { get; set; }
            /// <summary>
            /// 未生效
            /// </summary>
            public float WeiShengXiaoAll { get; set; }
            /// <summary>
            /// 业务员
            /// </summary>
            public string Salesman { get; set; }
        }

		#endregion
		#region AjaxResult AwardInfo() 奖励详情

		[HttpPost]
        public AjaxResult AwardInfo(AwardInfoParameter parameter)
        {
            int total = 0;            
			var data = _businessContract.UnitOfWork.DbContext.Queryable<UserRewardBusiness, Business, Users,UserRewardBusinessIncomeRunnings>((u, b, us,ub) => u.BusinessID == b.Id
			 && b.UserId == us.Id && ub.UserRewardBusinessID==b.Id ).OrderBy((u, b, us, ub) => u.CreatedTime)
			 .Where((u, b, us, ub) => u.Id == parameter.Id)
			.Select((u, b, us, ub) => new AwardInfoModel
			{
				Id = u.Id,
				Hashrate = u.Hashrate,
				BeginTime = u.BeginTime,
				EndTime = u.EndTime,
				CreatedTime = u.CreatedTime,
				AwardName = b.ProductName,
				UserName = us.UserName,
				ProductName = b.ProductName,
				BHashrate = b.Hashrate,	
				ShouYi = ub.Amount,
				ElectricCharge = ub.ElectricCharge,						
				Salesman = _unitOfWork.DbContext.Queryable<Users>().Single(p => p.Id == _unitOfWork.DbContext.Queryable<UserMap>().Single(it => it.UserId == us.Id && it.AgentId == b.UserId).AgentSalesmanId).UserName,
				DayIncome = Convert.ToDecimal(u.Hashrate) * BTCPoolDetails.Throughput,
			});

            AwardInfoModel entity = data.First() ?? new AwardInfoModel();

            //分页及数据处理            
            var list = data.ToPageList(parameter.Page, parameter.Limit, ref total);          
            //返回数据
            var result = new AwardInfoParameterModel
            {
                Rows = list,
                Total = total
            };
            return new AjaxResult("允许访问", AjaxResultType.Success, result);
        }
        public class AwardInfoParameter
        {
            public int Page { get; set; } = 1;
            public int Limit { get; set; } = 20;
			public int Id { get; set; }

        }

        public class AwardInfoParameterModel
        {
            public List<AwardInfoModel> Rows { get; set; } = new List<AwardInfoModel>();
            public int Total { get; set; }
        }

        public class AwardInfoModel
        {
            public int Id { get; set; }
            //奖励
            public float Hashrate { get; set; }
            public DateTime BeginTime { get; set; }
            public DateTime EndTime { get; set; }
            public DateTime CreatedTime { get; set; }
            public string AwardName { get; set; }
            //订单
            public string UserName { get; set; }
            /// <summary>
            /// 矿机名称
            /// </summary>
            public string ProductName { get; set; }
            /// <summary>
            /// 算力
            /// </summary>
            public decimal BHashrate { get; set; }
           
            /// <summary>
            /// 业务员
            /// </summary>
            public string Salesman { get; set; }
			/// <summary>
			/// 电费
			/// </summary>
			public decimal ElectricCharge { get; set; }
			/// <summary>
			/// 日产出
			/// </summary>
			public decimal DayIncome { get; set; }
			public decimal ShouYi { get; set; }

		}

        #endregion   
        #region AjaxResult MyGuest()

        [HttpPost]
        public AjaxResult MyGuest(MyGuestParameter parameter)
        {
            int total = 0;            
            var data = _unitOfWork.DbContext.Queryable<Product>().Where(m => m.Id == parameter.Id).Select(m => new ProductInfoModel
            {
                Id = m.Id,
                Name = m.Name,
                Hashrate = m.Hashrate,
                Inventory = m.Inventory,
                ElectricCharge = m.ElectricCharge,
                Price = m.Price,
                Effective = "永久",                
                Remark = m.Remark,
                Image = m.Image,

            });
            //分页及数据处理            
            var list = data.ToPageList(parameter.Page, parameter.Limit, ref total);
            //返回数据
            var result = new MyGuestParameterModel
            {
                Rows = list,
                Total = total
            };
            return new AjaxResult("允许访问", AjaxResultType.Success, result);
        }

        public class MyGuestModel
        {
            public int Id { get; set; }
            public string Name { get; set; }
            /// <summary>
            /// 算力
            /// </summary>
            public float Hashrate { get; set; }
            /// <summary>
            /// 净收益
            /// </summary>
            public int Inventory { get; set; }       


        }
        public class MyGuestParameter
        {
            public int Page { get; set; } = 1;
            public int Limit { get; set; } = 20;
            public int Id { get; set; }
        }

        public class MyGuestParameterModel
        {
            public List<ProductInfoModel> Rows { get; set; } = new List<ProductInfoModel>();
            public int Total { get; set; }
        }

        #endregion
        #region AjaxResult NoticeList() 公告列表

        [HttpPost]
        public AjaxResult NoticeList(NoticeParameter parameter)
        {
            int total = 0;
            var data = _unitOfWork.DbContext.Queryable<Notice>().Select(m => new NoticeModel
            {
                Id = m.Id,
                Title = m.Title,                
                Image = m.Image,
                CreateTime = m.CreateTime,
            });
            //分页及数据处理            
            var list = data.ToPageList(parameter.Page, parameter.Limit, ref total);
            //返回数据
            var result = new NoticeParameterModel
            {
                Rows = list,
                Total = total
            };
            return new AjaxResult("允许访问", AjaxResultType.Success, result);
        }

        public class NoticeModel
        {
            public int Id { get; set; }
            /// <summary>
            /// 标题
            /// </summary>
            public string Title { get; set; }            
            /// <summary>
            /// 图片
            /// </summary>
            public string Image { get; set; }
            /// <summary>
            /// 创建时间
            /// </summary>
            public string CreateTime { get; set; }
        }
        public class NoticeParameter
        {
            public int Page { get; set; } = 1;
            public int Limit { get; set; } = 20;
        }

        public class NoticeParameterModel
        {
            public List<NoticeModel> Rows { get; set; } = new List<NoticeModel>();
            public int Total { get; set; }
        }

        #endregion
        #region AjaxResult NoticeInfo()  公告详情

        [HttpPost]
        public AjaxResult NoticeInfo(NoticeInfoParameter parameter)
        {
            int total = 0;
            var data = _unitOfWork.DbContext.Queryable<Notice>().Where(m => m.Id == parameter.Id).Select(m => new NoticeInfoModel
            {
                Id = m.Id,
                Title = m.Title,
                Contents = m.Contents,
                Image = m.Image,
                CreateTime = m.CreateTime,
            });
            //分页及数据处理            
            var list = data.ToPageList(parameter.Page, parameter.Limit, ref total);
            //返回数据
            var result = new NoticeInfoParameterModel
            {
                Rows = list,
                Total = total 
            };
            return new AjaxResult("允许访问", AjaxResultType.Success, result);
        }

        public class NoticeInfoModel
        {
            public int Id { get; set; }
            /// <summary>
            /// 标题
            /// </summary>
            public string Title { get; set; }
            /// <summary>
            /// 内容
            /// </summary>
            public string Contents { get; set; }
            /// <summary>
            /// 图片
            /// </summary>
            public string Image { get; set; }
            /// <summary>
            /// 创建时间
            /// </summary>
            public string CreateTime { get; set; }
        }
        public class NoticeInfoParameter
        {
            public int Page { get; set; } = 1;
            public int Limit { get; set; } = 20;
            public int Id { get; set; }
        }

        public class NoticeInfoParameterModel
        {
            public List<NoticeInfoModel> Rows { get; set; } = new List<NoticeInfoModel>();
            public int Total { get; set; }
        }

        #endregion 
        #region AjaxResult NoticeIndexInfo() 首页公告

        [HttpPost]
        public AjaxResult NoticeIndexInfo()
        {
            var data = _unitOfWork.DbContext.Queryable<Notice>().OrderBy(m => m.CreateTime).Select(m => new NoticeIndexInfoModel
            {
                Id = m.Id,
                Title = m.Title,                
            });
           
            return new AjaxResult("允许访问", AjaxResultType.Success, data);
        }
        public class NoticeIndexInfoModel
        {
            public int Id { get; set; }
            /// <summary>
            /// 标题
            /// </summary>
            public string Title { get; set; }            
        }        

        #endregion
        #region AjaxResult PriceInfo() 首页价格

        [HttpPost]
        public AjaxResult PriceInfo()
        {
            var total = Math.Abs(BTCPoolDetails.PriceTrend) + BTCPoolDetails.Price;
            var data = new PriceModel
            {
                Price = BTCPoolDetails.Price,
                RMBPrice = BTCPoolDetails.Price * BTCPoolDetails.Exchange,
                PriceValue = BTCPoolDetails.PriceTrend > 0 ? BTCPoolDetails.PriceTrend / total : -(BTCPoolDetails.PriceTrend / total),
            };
            return new AjaxResult("允许访问", AjaxResultType.Success, data);
        }
        public class PriceModel
        {           
            /// <summary>
            /// 币价(美元)
            /// </summary>
            public decimal Price { get; set; }
            /// <summary>
            /// 币价（RMB）
            /// </summary>
            public decimal RMBPrice { get; set; }
            /// <summary>
            /// 增涨值
            /// </summary>
            public decimal PriceValue { get; set; }            
        }
        #endregion
        #region AjaxResult Machine() 矿机详情

        [HttpPost]
        public AjaxResult Machine(MachineParameter parameter)
        {
            int total = 0;
            var data = _unitOfWork.DbContext.Queryable<Machine>().Where(m => m.Id == parameter.Id).Select(m => new MachineModel
            {
                Id = m.Id,
                Name = m.Name,
                Kwh = m.Kwh,
                Hashrate = m.Hashrate,
                Power = m.Power,
                RateHashrate = m.RateHashrate,
                WallPower = m.WallPower,
                EnergyRate = m.EnergyRate,
                Voltage = m.Voltage,
                BoxSize = m.BoxSize,
                MachineSize = m.MachineSize,
                MachineWeight = m.MachineWeight,
                NewWork = m.NewWork,

            });
            //分页及数据处理            
            var list = data.ToPageList(parameter.Page, parameter.Limit, ref total); 
            //返回数据
            var result = new MachineParameterModel
            {
                Rows = list,
                Total = total
            };
            return new AjaxResult("允许访问", AjaxResultType.Success, result);
        }

        public class MachineModel
        {
            public int Id { get; set; }
            /// <summary>
            /// 矿机名称
            /// </summary>
            public string Name { get; set; }
            /// <summary>
            /// 功耗
            /// </summary>
            public float Kwh { get; set; }
            /// <summary>
            /// 算力
            /// </summary>
            public float Hashrate { get; set; }
            /// <summary>
            /// 功耗比
            /// </summary>
            public float Power { get; set; }
            /// <summary>
            /// 额定算力
            /// </summary>
            public float RateHashrate { get; set; }
            /// <summary>
            /// 墙上功耗
            /// </summary>
            public float WallPower { get; set; }
            /// <summary>
            /// 能耗比
            /// </summary>
            public float EnergyRate { get; set; }
            /// <summary>
            /// 客定电压
            /// </summary>
            public string Voltage { get; set; }
            /// <summary>
            /// 外箱尺寸
            /// </summary>
            public string BoxSize { get; set; }
            /// <summary>
            /// 机器尺寸
            /// </summary>
            public string MachineSize { get; set; }
            /// <summary>
            /// 机器重量
            /// </summary>
            public float MachineWeight { get; set; }
            /// <summary>
            /// 网络连接
            /// </summary>
            public string NewWork { get; set; }
        }
        public class MachineParameter
        {
            public int Page { get; set; } = 1;
            public int Limit { get; set; } = 20;
            public int Id { get; set; }
        }

        public class MachineParameterModel
        {
            public List<MachineModel> Rows { get; set; } = new List<MachineModel>();
            public int Total { get; set; }
        }

        #endregion
    }
}
